package org.wpahs.ahn.rssfeed;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Base64;
import android.util.Log;
import android.util.Xml;
import android.webkit.URLUtil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.wpahs.ahn.rssfeed.DB.DBFeedItem;
import org.wpahs.ahn.rssfeed.DB.DBMyFeed;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

/**
 * RSSGetService does all the HTTP work
 * Created by dgambone on 01/12/2015.
 */
public class RSSGetService extends IntentService {

    Context mContext = null;

    public static final String NOTIFICATION = "org.wpahs.ahn.rssfeed.serviceupdate";
    public static final String FEED_START = "org.wpahs.ahn.rssfeed.start";
    public static final String FEED_DONE = "org.wpahs.ahn.rssfeed.done";
    public static final String FEEDITEM_IMAGE_DONE = "org.wpahs.ahn.rssfeed.feeditemimagedone";
    public static final String FEED_IMAGE_DONE = "org.wpahs.ahn.rssfeed.feedimagedone";


    private final IBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {

        RSSGetService getService(){
            return RSSGetService.this;
        }
    }


    @Override
    public IBinder onBind(Intent intent){
        return mBinder;
    }

    public RSSGetService(){
        super("org.wpahs.ahn.rssfeed.RSSGetService");
    }
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public RSSGetService(String name) {
        super(name);
    }



    @Override
    protected void onHandleIntent(Intent intent) {
        int feedId = 0;
        mContext = getApplicationContext();
        feedId = intent.getIntExtra(mContext.getString(R.string.feed_id), feedId);
        process(feedId, false);
    }
    private boolean getAutoPoll(){
        if(mContext==null){
            mContext = getApplicationContext();
        }
        SharedPreferences prefs=
                mContext.getSharedPreferences(
                        mContext.getString(
                                R.string.preferences_gambonereader),
                        Context.MODE_PRIVATE);
        return prefs.getBoolean(
                mContext.getString(R.string.preferences_enableAuto),
                false);

    }

    private int getAutoPollMinutes(){
        if(mContext==null){
            mContext = getApplicationContext();
        }
        SharedPreferences prefs=
                mContext.getSharedPreferences(
                        mContext.getString(
                                R.string.preferences_gambonereader),
                        Context.MODE_PRIVATE);
        return prefs.getInt(
                mContext.getString(R.string.preference_autoPollInMinutes),
                -1);

    }
    public void process(int feedId, boolean manual){

        if(!getAutoPoll() && !manual){
            broadcastFeedDone(feedId,"");
            return;
        }
        if(feedId == 0){ // get em all
            DBMyFeed fs = new DBMyFeed(this);
            List<MyFeed> feeds = fs.GetFeeds(false);
            fs.close();
            List<MyFeed> list = new ArrayList<MyFeed>();

            for(MyFeed feed : feeds) {
                list.add(feed);
            }
            new FeedGetter(list,mContext).execute();
            broadcastStart(0, "All");
        }else if(feedId >0){ // just get one
            DBMyFeed fs = new DBMyFeed(this);
            MyFeed oneFeed = fs.getFeed(feedId);
            fs.close();
            if(oneFeed != null) {
                List<MyFeed> list = new ArrayList<MyFeed>();
                list.add(oneFeed);
                broadcastStart(feedId, oneFeed.getTitle());
                new FeedGetter(list,mContext).execute();
            }else{
                broadcastFeedDone(feedId,"");
            }
        }else{
            Log.i("RSSGetService", "Did nothing");
            broadcastFeedDone(0,"");
        }
    }

    private boolean isConnectedViaWifi() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifi.isConnected();
    }



    private void broadcastStatus(int feedId, String title, String status){
        Intent intent = new Intent(NOTIFICATION);
        intent.putExtra(getString(R.string.feed_id), feedId);
        intent.putExtra(getString(R.string.feedTitle), title);
        intent.putExtra(getString(R.string.status), status);
        sendBroadcast(intent);
    }

    private void broadcastStart(int feedId, String title){
        Intent intent = new Intent(FEED_START);
        intent.putExtra(getString(R.string.feed_id), feedId);
        intent.putExtra(getString(R.string.feedTitle), title);
        sendBroadcast(intent);
    }

    private void broadcastFeedDone(int feedId, String title){
        Intent intent = new Intent(FEED_DONE);
        intent.putExtra(getString(R.string.feed_id), feedId);
        intent.putExtra(getString(R.string.feedTitle), title);
        sendBroadcast(intent);
    }

    private void broadcastFeedImageDone(int feedId){
        Intent intent = new Intent(FEED_IMAGE_DONE);
        intent.putExtra(getString(R.string.feed_id), feedId);
        sendBroadcast(intent);
    }

    @Override
    public void onDestroy(){
        Log.i("RSSGetService", "Destroyed");
        super.onDestroy();
    }



}
